﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using BaseNet.Core.Attribute;

namespace BaseNet.Core.Utils
{
    /// <summary>
    /// input入参批量赋值给实体类
    /// </summary>
    public class InputSetEntityHelper
    {
        /// <summary>
        /// input对象批量赋值给entity
        /// 用于修改实体时字段的批量赋值
        /// </summary>
        /// <typeparam name="T_input"></typeparam>
        /// <typeparam name="T_entity"></typeparam>
        /// <param name="input"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static void InputSetEntity<T_input, T_entity>(T_input input,ref T_entity entity)
        {
            foreach (PropertyInfo p in typeof(T_input).GetProperties())//遍历入参，判断入参中是否包含InputSetEntityAttribute头缀，包含即赋值
            {
                var inputSetEntityAttribute = System.Attribute.GetCustomAttribute(p, typeof(InputSetEntityAttribute)) as InputSetEntityAttribute;
                if (inputSetEntityAttribute != null)//判断是否具有InputSetEntityAttribute
                {
                    //实体类所对应的属性
                    var entityValue = typeof(T_entity).GetProperty(p.Name).GetValue(entity);
                    var inputValue = p.GetValue(input);
                    if (inputValue != entityValue)
                    {
                        typeof(T_entity).GetProperty(p.Name).SetValue(entity, inputValue);
                    }
                }
            }
        }
    }
}
